#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
int main(){
    /*
     * 1、创建服务端套接字（侦听套接字）
     * 2、绑定地址信息
     * 3、监听
     * 4、获取新连接
     * 5、收发消息
     * */
    int listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(listen_fd < 0){
        perror("socket");
        return 0;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(22222);
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");
    
    int ret = bind(listen_fd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret < 0){
        perror("bind");
        return 0;
    }
    //监听
    ret = listen(listen_fd, 5);
    if(ret < 0){
        perror("listen");
        return 0;
    }
    //接收新连接
    struct sockaddr_in cli_addr;
    socklen_t cli_addr_len = sizeof(cli_addr);
    int new_sockfd = accept(listen_fd, (struct sockaddr*)&cli_addr, &cli_addr_len);
    if(new_sockfd < 0){
        perror("accept");
        return 0;
    }
    //收发消息
    while(1){
        char buf[1024] = {0};
        int recv_size = recv(new_sockfd, buf, sizeof(buf) - 1, 0);
        if(recv_size < 0){
            perror("recv");
            return 0;
        }else if(recv_size == 0){
            //客户端将连接关闭了
            printf("perr shutdown\n");
            close(new_sockfd);
            return 0;
        }
        printf("buf is [%s]\n", buf);
        memset(buf, '\0', sizeof(buf));
        //发送消息
        sprintf(buf, "[%s]:[%d] I am serve, i recv your msg", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
        send(new_sockfd, buf, strlen(buf), 0);
    }
    close(listen_fd);
    return 0;
}
